package com.qk.management.web.interceptor;

import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.Optional;

/**
 * @Author: chouh
 * @DateTime: 2025/10/11 14:53
 * @Description:
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    private static final String TOKEN_HEADER_NAME = "token";


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (Optional.ofNullable(token).isEmpty()) {
            log.info("token is null");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        try {
           Claims claims = JwtUtil.parseToken(token);
            Integer id = claims.get("id", Integer.class);
            log.info("userId: {}", id);
            String username = claims.get("username", String.class);
            log.info("username: {}", username);
        } catch (Exception e) {
            log.info("解析token失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }
}
